package com.springboot.demo.count.str;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

/**
 * 字符数量统计
 *
 * @author supu
 * @date 2019-12-12 16:06
 **/
public class CharCountDemo {
    private String src = "wqeraadce123jkadf";

    @Test
    public void getStrCountTest() {
        String origin = "aa";
        System.out.println(origin + "个数：" + getStrCount(src, origin));
    }

    @Test
    public void getCharCountTest() {
        System.out.println(getCharCount(src));
    }

    public int getStrCount(String src, String origin) {
        int count = 0;
        int index = -1;
        while ((index = src.indexOf(origin, index + 1)) > -1) {
            count++;
        }
        return count;
    }

    public Map<Character, Integer> getCharCount(String src) {
        int[] num = new int[26];
        Map<Character, Integer> charCountMap = new HashMap<>(16);
        for (char c : src.toCharArray()) {
            if (c >= 97 && c <= 123) {
                num[c - 97]++;
            }
        }

        for (int i = 0; i < num.length; i++) {
            if (num[i] > 0) {
                charCountMap.put((char) (i + 97), num[i]);
//                System.out.println( (char) (i + 97) + " 个数：" + num[i]);
            }
        }

        return charCountMap;
    }
}
